//
//  CompetitionViewController.m
//  CoolRollerSkating
//
//  Created by 谢伟康 on 15/11/9.
//  Copyright © 2015年 Coollang. All rights reserved.
//

#import "CompetitionViewController.h"
#import "CompetitionTableViewCell.h"
#import "RankModel.h"
#import "MyRankModel.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "UIImageView+CM_ShowImage.h"
#import <HMSegmentedControl/HMSegmentedControl.h>
#import "CoollangTennisBall-Swift.h"
#import "PhotoActionSheetViewController.h"
#import "NSBundle+CurrentLanguage.h"
#import "UIView+Frame.h"
#import "CompetitionAPi.h"

static NSString * const kTopRankCellIdentifier = @"TopRankCell";

@interface CompetitionViewController ()<UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *rankingLabel;
@property (weak, nonatomic) IBOutlet UILabel *kilometerLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong,nonatomic) MyRankModel *myInfo;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (copy, nonatomic) NSArray <RankModel *> *dataSouce;
@property (assign, nonatomic) RankModeType rankMode;

@property (weak, nonatomic) IBOutlet UILabel *rankDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *swingCountDescriptionLabel;
@property (weak, nonatomic) IBOutlet HMSegmentedControl *topSegmentedControl;
@property (weak, nonatomic) IBOutlet UILabel *signatureLabel;

@property (nonatomic, strong) NSArray *calculateRankItems;
@property (weak, nonatomic) IBOutlet UISegmentedControl *rankModeSegmentedControl;
@property (weak, nonatomic) IBOutlet UIView *uploadHeadIconView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topTipsHeightConstraint;
@property (weak, nonatomic) IBOutlet UILabel *uploadImageDescriptionLabel;
@property (weak, nonatomic) IBOutlet UIButton *uploadImageButton;

@end

@implementation CompetitionViewController


#pragma mark - ViewLifeCircle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureLocalization];
 
    [self configureBaseData];
    [self configureTableView];
    [self addRefresh];
    [self configureTopSegmentedControl];
    
    if (![NSBundle currentLanguageIsChinese]) {
        self.topTipsHeightConstraint.constant = 0;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - Localization

- (void)configureLocalization
{
    self.rankDescriptionLabel.text = NSLocalizedString(@"NO.", nil);
    self.swingCountDescriptionLabel.text = NSLocalizedString(@"Shots", nil);
    
    [self.rankModeSegmentedControl setTitle:NSLocalizedString(@"Shots", nil) forSegmentAtIndex:0];
    [self.rankModeSegmentedControl setTitle:NSLocalizedString(@"Avg Score", nil) forSegmentAtIndex:1];
    
    NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"Upload your profile picture to get the ranking!", nil)];
    NSAttributedString *uploadText = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"Click Upload", nil) attributes:@{
                                                                                                                                       NSUnderlineStyleAttributeName: @1,
                                                                                                                                       NSUnderlineColorAttributeName: kOrangeColor,
                                                                                                                                       NSForegroundColorAttributeName: kOrangeColor
                                                                                                                        }];
    
    [mutableAttributedString appendAttributedString:uploadText];
    self.uploadImageDescriptionLabel.attributedText = mutableAttributedString;
}

#pragma mark - IBAction

- (IBAction)uploadImage:(UIGestureRecognizer *)sender {
    
    __weak typeof(self) weakSelf = self;
    [PhotoActionSheetViewController showInParentViewController:self animationType:DetailViewControllerPresentAnimationTypeUp actionBlock:^(kTapActionButtonType btnType) {
        if (btnType == kTapAlbumButton) {
            [weakSelf takePhotoByPhotos];
        }else if(btnType == kTapCameraButton){
            [weakSelf takePhotoByCamera];
        }
    }];
}

- (IBAction)showHeadIcon:(id)sender {
    [self.headImageView showImage];
}

- (IBAction)changeRankMode:(UISegmentedControl *)sender {
    switch (sender.selectedSegmentIndex) {
        case 0: self.rankMode = RankModeTypeSwings; break;
        case 1: self.rankMode = RankModeTypeAvgScore; break;
        default: break;
    }
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - Private Method
- (void)configureTopSegmentedControl {
    if ([NSBundle currentLangeuage] == kLanguageFrennch) {
       self.topSegmentedControl.width = 200;
    }
    self.topSegmentedControl.sectionTitles =@[NSLocalizedString(@"Monthly Ranking", nil), NSLocalizedString(@"Total Ranking", nil)];
    
    __weak CompetitionViewController *weakSelf = self;
    [self.topSegmentedControl setIndexChangeBlock:^(NSInteger index) {
        NSLog(@"Selected index %ld (via block)", (long)index);
        [weakSelf.tableView.mj_header beginRefreshing];
    }];
    
    self.topSegmentedControl.selectionIndicatorHeight = 3.0f;
    self.topSegmentedControl.backgroundColor = [UIColor clearColor];
    
    CGFloat fontSize = [NSBundle currentLanguageIsChinese] ? 17.0f : 12.0f;
    self.topSegmentedControl.selectedTitleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName: MYFONT(fontSize)};
    self.topSegmentedControl.titleTextAttributes =@{NSForegroundColorAttributeName : [UIColor colorWithWhite:1 alpha:0.5f], NSFontAttributeName: MYFONT(fontSize)};
    self.topSegmentedControl.selectionIndicatorColor = [UIColor whiteColor];
    self.topSegmentedControl.selectionIndicatorBoxOpacity = 0.8;
    self.topSegmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
    self.topSegmentedControl.selectedSegmentIndex = 0;
    self.topSegmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    self.topSegmentedControl.shouldAnimateUserSelection = YES;
}

- (void)configureBaseData
{
    self.dataSouce = [NSArray array];
    self.rankMode = RankModeTypeSwings;
}

- (void)configureUI {
    if (self.myInfo) {
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:self.myInfo.headIcon] placeholderImage:[UIImage imageNamed:@"competition_icon_defaulImage"]];
        self.rankingLabel.text   = [NSString stringWithFormat:@"%@",self.myInfo.number];
        self.uploadHeadIconView.hidden = (self.myInfo.headIcon.length > 0);
    }
    self.headImageView.layer.masksToBounds = YES;
    self.headImageView.layer.cornerRadius = self.headImageView.frame.size.width/2;
    
    self.userNameLabel.text = self.myInfo.userName;
    self.signatureLabel.text = self.myInfo.signature;
    
    NSString *changeString = nil;
    NSAttributedString *unitString = nil;
    
    switch (self.rankMode) {
        case RankModeTypeSwings:
            changeString = self.myInfo.totalCount;
            unitString = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"Sport.Unit.Shots", nil) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10.0f]}];
            break;
        case RankModeTypeAvgScore:
            changeString = self.myInfo.maxScore;
            unitString = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"Unit.Score", nil) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10.0f]}];
            break;
        case RankModeTypeMaxSpeed:
            changeString = self.myInfo.maxspeed;
            unitString = [[NSAttributedString alloc] initWithString:@"km/h" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10.0f]}];
            break;
            
    }
    
    NSAttributedString *attributeString = [[NSAttributedString alloc] initWithString:changeString attributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:24.0]}];
    NSMutableAttributedString *data = [[NSMutableAttributedString alloc] initWithAttributedString:attributeString];
    [data appendAttributedString:unitString];
    self.kilometerLabel.attributedText = data;
}

- (void)configureTableView
{
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView registerNib:[UINib nibWithNibName:@"CompetitionTableViewCell" bundle:nil] forCellReuseIdentifier:@"CompetitionTableViewCell"];
    self.tableView.allowsSelection = NO;
}

#pragma mark - Refresh Data
- (void)addRefresh{
    [self.tableView addLegendHeaderWithShowTime:NO RefreshingBlock:^{
         [self requestData];
    }];
}

- (void)requestData{
    CompetitionAPi *api = [[CompetitionAPi alloc] initWithRankType:[@(self.rankModeSegmentedControl.selectedSegmentIndex + 1) stringValue] timePeriod:[@(self.topSegmentedControl.selectedSegmentIndex) stringValue]];
    [[YFNetworkingService sharedInstance] sendRequest:api callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            self.myInfo = api.myRankItem;
            self.dataSouce = [self calculateRankItemsFromOrignalRankItems:api.rankItems];
            [self configureUI];
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
    }];

}

- (NSArray *)calculateRankItemsFromOrignalRankItems:(NSArray *)rankItems
{
    NSMutableArray *calculateRankItems = [@[] mutableCopy];
    NSMutableArray *topRankItems = [@[] mutableCopy];
    [calculateRankItems addObject:topRankItems];
    
    for (NSInteger index = 0; index < [rankItems count]; index++) {
        if (index < 3) {
            [topRankItems addObject:rankItems[index]];
        } else {
            [calculateRankItems addObject:rankItems[index]];
        }
    }
    
    return [calculateRankItems copy];
}



#pragma mark - UITableView DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSouce.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        TopRankCell *cell = [tableView dequeueReusableCellWithIdentifier:kTopRankCellIdentifier forIndexPath:indexPath];
        
        [cell configureWithTopRankItems:self.dataSouce[indexPath.row] rankModeType:self.rankMode];
        
        return cell;
    } else {
        CompetitionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CompetitionTableViewCell"];
        if (self.dataSouce.count > indexPath.row) {
            [cell configureCompetitionCellByModel:self.dataSouce[indexPath.row]
                                        indexPath:indexPath
                                             rankModeType:self.rankMode];
        }
        
        return cell;
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row > 0) {
        return 59.0f;
    } else {
        return 175.0f;
    }
}

#pragma mark - <从手机中选择图片>

- (void)takePhotoByCamera{
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Can't get camera or photo information", nil) inView:self.view];
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)takePhotoByPhotos{
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Can't get camera or photo information", nil) inView:self.view];
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIImagePickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [YFUserApi uploadImageWithRequestType:kUserUploadHeadImage withImage:image complete:^(NSError *error, NSString *imageUrl) {
        [hud hideAnimated:YES];
        if (error == nil) {
            self.headImageView.image = image;
            NSString *imageUrl = imageUrl;
            
            [[RLMRealm defaultRealm] beginWriteTransaction];
            [User getLastUser].userInforItem.headIconPath = imageUrl;
            [[RLMRealm defaultRealm] commitWriteTransaction];
            [self.tableView.mj_header beginRefreshing];
        }
    }];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
}

@end
